<template>
  <div class="loginContainer">
    <video data-v-73443695="" muted="muted" src="../../assets/video/bgv.mp4" loop="loop" autoplay="autoplay" class="video"></video>
    <el-form :model="loginForm" status-icon :rules="rules" ref="loginForm" label-width="100px" class="demo-loginForm">
      <h1 class="title" v-text="title"></h1>
      <i @click="isErweiLogin=!isErweiLogin,sms=false" :class="['iconfont','jiaobiao',jiaobiao]"></i>
      <!-- 常规登录 -->
      <div class="common-login" v-if="!isErweiLogin && !sms">
        <el-form-item label="用户名" prop="username">
          <el-input type="text" v-model="loginForm.username" autocomplete="on"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="loginForm.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="captcha">
            <el-input maxlength="5" class="captcha" v-model="loginForm.captcha" @keydown.native.enter="submitForm('loginForm')"></el-input>
            <span class="captcha-svg"
						v-loading="loading">
						<i @click="updateCaptcha"
							v-html="captchaSvg"></i>
					</span>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="submitForm('loginForm')">登录</el-button>
        </el-form-item>
        <!-- 底部短信切换 -->
        <el-form-item>
					<div class="sms">
						<svg class="icon"
							aria-hidden="true">
							<use xlink:href="#icon-iphone"></use>
						</svg>
						<a href="javascript:;" @click="sms=true"
							style="color: #fff; font-size: 16px">切换短信登入</a>
					</div>
				</el-form-item>
      </div>
      <!-- 二维码登录 -->
      <div class="erwei" v-else-if="isErweiLogin && !sms">
        <div class="img" v-loading="qrLoading">
          <img :src="imgBase64Url" alt="">
          <i class="mask" :style="qrStyle" v-show="showQrMask" @click="getQrCode"></i>
        </div>
        <p class="bottomText">
          <svg class="icon icon-wx"
							aria-hidden="true">
							<use xlink:href="#icon-weixin"></use>
						</svg>
          <b v-text="qrTip"></b>
        </p>
      </div>
      <!-- 手机登录 -->
       <div class="smsContainer" v-else>
        <el-form-item label="手机号">
          <el-input maxlength="11" v-model="phoneNumber" class="captcha phone"></el-input>
          <span @click="sendSmsCode" class="captcha-svg smsCaptcha" v-text="smsRetryMsg" style="color:#888;line-height:45px;text-decoration:underline"></span>
        </el-form-item>
        <el-form-item label="验证码">
          <el-input v-model="smsCode"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="smsSubmit" >提交</el-button> 
        </el-form-item>
      </div>
    </el-form>
  </div>
    
</template>

<script>
  import successCodePic from "../../assets/img/scancode.png"
  import failCodePic from "../../assets/img/invalidQr.png"
  import socketIo from "socket.io-client"
  import qr from "qrcode"
  import { mapMutations } from "vuex"
  //校验验证码
  var validateCaptcha = (rule, value, callback) => {
    if(!value){
        callback("请正确输入验证码")
    }else{
        callback()
    }
  };
    //校验用户名
  var validateUsername = (rule, value, callback) => {
    let pattern = /^[a-zA-Z0-9_-]{1,16}$/;
    if(pattern.test(value)){
        callback();
        } else {
            callback("请输入4到16位（字母，数字，下划线，减号）")
        }
    };
    //校验密码
  var validatePassword = (rule, value, callback) => {
    if (value === '') {
      callback(new Error('请输入密码'));
    } else {
      callback();
    }
  };
  import * as api from "@/api/Users"

  export default {
    name:"login",
    data() {
      return {
        smsDisabled: false,//控制是否能够再次发送
        title:"千锋管理系统",
        loading:true,
        isErweiLogin:false,
        qrTip:"请使用手机微信扫码登入",
        qrLoading:true,//加载二维码的loading动画
        sms:false,
        phoneNumber:"",//手机号
        smsRetryMsg:"点击发送验证码",//**秒后重新发送
        smsCode:"",//短信验证码
        captchaSvg:"",
        imgBase64Url:"",//二维码图片地址
        showQrMask:false,//二维码遮罩
        loginForm: {
          username: '',
          password: '',
          captcha: '',
        },
        rules: {
          username: [
            { validator: validateUsername, trigger: 'blur' }
          ],
          password: [
            { validator: validatePassword, trigger: 'blur' }
          ],
          captcha: [
            { validator: validateCaptcha, trigger: 'blur' }
          ]
        },
        qrStyle: {
          backgroundImage:`url(${failCodePic})`
        },
      };
    },
    computed:{
      jiaobiao(){
        return this.isErweiLogin
              ?'icon-diannaojiaobiao'
              :'icon-erweimajiaobiao'
      }
    },
    created(){
      this.updateCaptcha();
    },
    methods: {
      //映射vuex的mutation
      ...mapMutations(['SET_USERINFO']),
      async sendSmsCode(){
        console.log(this.phoneNumber);
        if(this.smsDisabled){
          this.$message.error("1分钟内只能发送一次")
          return
        }
        let smsResult = await api.getSmsCode(this.phoneNumber);
        console.log(smsResult);
        let {state}=smsResult.data;
        if(state){
          // 锁住smsDisabled，不能再次发送
          this.smsDisabled = true;
          this.$message.success('短信发送成功');
          this.smsSecond = 60;
          this.smsInterval = setInterval(()=>{
          this.smsSecond--;
          if(this.smsSecond ===0){
            //清除定时器
            clearInterval(this.smsInterval);
            //提示文字要复原
            this.smsRetryMsg = '点击发送验证码'
            this.smsDisabled = false;
            return
          }
          this.smsRetryMsg = `${this.smsSecond}秒后重新发送`
        },1000)
        }
      },
      async smsSubmit(){
        let smsLoginRes = await api.smsLogin(this.smsCode)
        console.log(smsLoginRes);
        let {userInfo,state,permission:{buttons},token} = smsLoginRes.data;
        if(state){
          localStorage.setItem('wqj-userInfo',JSON.stringify(userInfo))
          localStorage.setItem('wqj-permissionBtn',JSON.stringify(buttons))
          localStorage.setItem('wqj-token',token)
          //调用vuex的方法，设置用户信息
          this.SET_USERINFO(userInfo)

          this.$router.push("/")
        }
      },
      submitForm(formName) {
        this.$refs['loginForm'].validate((valid) => {
          if (valid) {
            //打开加载动画
            const loading = this.$loading({
              lock: true,
              text: '正在加载',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            });
        setTimeout(() => {
          loading.close();
        }, 2000);
            //本地表单校验通过
            let {username,password,captcha}=this.loginForm;
            //校验验证码
            api.verifyCaptcha(captcha)
            .then(async (res)=>{
              // console.log(res);
              let {state} = res.data;
              if(state){
                let loginRes = await api.login(username,password);
                // console.log(loginRes);
                let {state:loginState,msg,token,userInfo} = loginRes.data;
                if(loginState){
                  //登入成功
                  //关闭登入加载动画
                  loading.close();
                  //将token存到localStorage
                  localStorage.setItem('wqj-token',token)
                  //调用vuex的方法，设置用户信息
                  this.SET_USERINFO(userInfo)
                  //跳转页面
                  this.$router.push("/")
                  this.$message({
                    message: msg,
                    type: 'success',
                    duration: 1000
                  })
                }else{
                  //登入失败也要关闭加载动画
                  loading.close();
                }
              }else{
                  //登入失败也要关闭加载动画
                  loading.close();
                  //刷新验证码
                  this.updateCaptcha()
                }
            });
          } else {
            alert('不通过')
          }
        });
      },
      //封装一个方法，专门用于获取验证码
      updateCaptcha(){
        this.loading = true;
        api.getCaptcha()
        .then(res=>{
          // console.log(res)
          let {img} = res.data;//解构验证码
          this.captchaSvg = img;
          this.loading = false;
        })
      },
      async getQrCode(sid){
        //转换二维码下面的提示文字
        this.qrTip = "请使用手机微信扫码登入";
        //先关遮罩
        this.showQrMask = false;
        //加载动画
        this.qrLoading = true;
        sid = localStorage.getItem('wqj-sid') ?? sid;
        console.log(sid)
        let qrResult = await api.getQrcode(sid);
            // console.log(qrResult);

            let{scanCodeUrl,state:getQrState}=qrResult.data
            // console.log(scanCodeUrl);

            if(getQrState){
              qr.toDataURL(scanCodeUrl,(err,imgBase64Url)=>{
                if(err){
                  this.$messageBox.error(err);
                  return
                }
                // console.log(imgBase64Url);
                this.imgBase64Url=imgBase64Url;

                //关掉二维码加载动画
                this.qrLoading = false;
              })
            }
      }
    },
    watch:{
      //监听切换短信登入逻辑
      sms(val){
        if(!val){
          if(this.smsInterval){
            clearInterval(this.smsInterval)
          }
          this.smsRetryMsg = "点击发送验证码"
        }
      },
      isErweiLogin(isErwei){
        if(isErwei){
          //打开二维码登入
          this.qrLoading = true;
          //把遮罩关掉
          this.showQrMask = false;
          //建立socket连接
          let io = socketIo("wss://chst.vip")
          //扫码成功
          io.on('scancodeSuccess',async data=>{
            //显示二维码遮罩 并将背景图片换成扫码成功的背景图片
            this.showQrMask = true;
            this.qrStyle.backgroundImage = `url(${successCodePic})`
            console.log(data)
            let{state:scanCodeState, wechatCode}= data
            if(scanCodeState){
              let scanCodeRes = await api.wechatLogin(wechatCode)
              console.log(scanCodeRes);
              let{state,userInfo,permission:{buttons},token} = scanCodeRes.data;
              if(state){
                localStorage.setItem('wqj-userInfo',JSON.stringify(userInfo))
                localStorage.setItem('wqj-permissionBtn',JSON.stringify(buttons))
                localStorage.setItem('wqj-token',token)
                //调用vuex的方法，设置用户信息
                  this.SET_USERINFO(userInfo)

                this.$router.push("/welcome")
                //跳转成功就关闭二维码遮罩
                this.showQrMask = false;
              }
            }
          })
          //二维码失效
          io.on('invalidCode',data=>{
            console.log(data);
            let{state}=data;
            if(!state){
              this.showQrMask=true;
              this.qrTip = "二维码已失效，请重新获取"
            }
          })
          //连接成功
          io.on("connectSuccess",async (data)=>{
            // console.log(data)
            let {sid} = data;
            localStorage.setItem("wqj-sid",sid)
            //调用获取二维码的方法
            this.getQrCode(sid)
            
          })
        }
      }
    },
  }
</script>
<style lang="less" scoped>
    // 找类名
    // 看权重
    // 看是否是深度选择器
  .video{
    position: fixed;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
  }
  .icon-wx{
    width: 1.5em;
    height: 1.5em;
    vertical-align: -0.6em;
    fill: currentColor;
    overflow: hidden;
  }
  .elform{
    position: fixed;
    right: 10%;
    top: 25%;
    border-radius: 5px;
    width: 400px;
    background-color: rgba(0,0,0,.3);
    padding: 100px 0 50px 0;
  }
    .demo-loginForm{
      position: fixed;
      right: 10%;
      top: 25%;
      border-radius: 5px;
      width: 400px;
      background-color: rgba(0,0,0,.3);
      padding: 100px 0 50px 0;
    }
    .title{
      margin: 0 0 60px 0;
      text-align: center;
      color: #fff;
    }
    /deep/ .el-form-item__label {
    color: #fff;
    }
    //二维码样式
    .erwei .img {
      display: inline-block;
      position: relative;
      width: 200px;
      height: 200px;
      margin-left: 100px;

      img {
        position: absolute;
        // left: 100px;
        width: 200px;
        height: 200px;
      }

      .mask {
        width: 100%;
        height: 100%;
        opacity: 0.8;
        background-color: #fff;
        position: absolute;
        // left: 100px;
        background-image: url("../../assets/img/scancode.png");
        background-size: 50%;
        background-repeat: no-repeat;
        background-position: center;
        cursor: pointer;
      }
      
	  }
    .bottomText{
                text-align: center;
                color: #fff;
          }
    //角标样式
    .jiaobiao{
      font-size: 60px;
      color: #fff;
      position: absolute;
      right: -1px;
      top: -1px;
      cursor: pointer;
      opacity: .7;
    }
    el-form-item{
      margin-bottom: 22px;
    }
    .el-input{
      position: relative;
      font-size: 14px;
      display: inline-block;
      width: 100%;
      /deep/ .el-input__inner{
            position: relative;
            font-size: 14px;
            display: inline-block;
            width: 250px;;
      }
    }
    .captcha {
    width: 100px;
		vertical-align: top;
      /deep/.el-input__inner{
        width: 100%;
				height: 45px;
				border-radius: 5px 0 0 5px;
				border: 0;
				font-size: 18px;
      }
    }
    .captcha-svg{
      background: #fff;
      display: inline-block;
      height: 45px;
      width: 150px;
      text-align: center;
      cursor: pointer;
      border: 0;
      border-radius: 0px 5px 5px 0;
    }
    .smsCaptcha{
      width:115px
    }
    .phone{
      width:135px
    }
    .el-button{
      width: 80%;
      background: linear-gradient(90deg,#1596fb,#002dff);
    }
  .icon-wx {
    width: 25px !important;
    height: 25px !important;
    vertical-align: -7px;
    margin-right: 3px;
  }
  
</style>